package com.atguigu.realtime.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.common.Constant;
import org.apache.commons.collections.CollectionUtils;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.util.List;

import static com.atguigu.realtime.common.Constant.DIM_EXPIRE_SECOND;

/**
 * Created by RUI on 2021/6/28 21:07
 */
public class DimUtil {


    public static JSONObject readDim(Connection conn, Jedis jedis, String table, Object id) throws Exception {

        //先从redis里读数据,缓存没有再从hbase中读取
        JSONObject dim = readDimFromCache(jedis, table, id);

        if (null == dim){
            System.out.println("从 Phoenix  读取维度:" + table + "  " + id);
            dim = readDimFromPhoenix(conn,table,id);
            // 把这次读到的dim数据存储到缓存中
            saveDimToCache(jedis, table, id, dim);
        }else {
            System.out.println("从 缓存  读取维度: " + table + "  " + id);
        }

        return dim;
    }

    private static void saveDimToCache(Jedis jedis, String table, Object id, JSONObject dim) {
        String key = table + ":" + id;

        jedis.setex(key,DIM_EXPIRE_SECOND,dim.toJSONString());
    }

    private static JSONObject readDimFromCache(Jedis jedis, String table, Object id) {
        String key = table + ":" + id;
        String jsonStr = jedis.get(key);

        JSONObject dim = null;

        if (jsonStr != null) {
            dim = JSON.parseObject(jsonStr);
            // 每读一个维度, 应该重新计算一个24小时的过期时间   更新过期时间
            jedis.expire(key, DIM_EXPIRE_SECOND);
        }

        return dim;
    }

    public static JSONObject readDimFromPhoenix(Connection conn,
                                                String table,
                                                Object id) throws Exception {
        String sql = "select * from " + table + " where id=?";

        // 可以执行各种sql, 查询的结果应该会有多行
        List<JSONObject> list = JDBCUtil.queryList(conn, sql, new Object[]{id.toString()}, JSONObject.class);

        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        }
        return new JSONObject();
    }

    public static void main(String[] args) throws Exception {
        Connection conn = JDBCUtil.getJdbcConnection(Constant.PHOENIX_DRIVER, Constant.PHOENIX_URL);
        JSONObject object = readDimFromPhoenix(conn, "dim_user_info", 999);
        System.out.println(object);
    }
}
